/********** WebSocket ***********/
var start = false;
var turn = false;
var usr = rand();
var rival = "";
var ws = new WebSocket("ws://47.100.89.85:8013");
//var ws = new WebSocket("ws://localhost:8013");
ws.onopen = function(evt) {onOpen(evt)};
ws.onmessage = function(evt) {onMessage(evt)};
ws.onclose = function(evt) { onClose(evt) };
ws.onerror = function(evt) { onError(evt) };

// window.onbeforeunload = function() {
//     console.log("Here Close");
//     ws.close();
// }  

function rand() {
    var base = 100000000;
    var id = parseInt(Math.random()*base,10);
    //console.log(id); 
    return id;
}

// function login() {
//     var usr = document.getElementById("inputName").value;
//     if(!start) {
//         sendMsg("1 " + usr);
//     }
//     if(start) {
//         //window.location.href="../html/gomoku.html";
//         console.log("Login");
//     }
// }

function onOpen(evt){
    console.log("open");
    isconnect = true;
    sendMsg("1 " + usr);
}

function onMessage(evt) {
    var str = evt.data.split(" ");
    console.log(str);
    if(parseInt(str[0]) == "1") {
        rival = str[1];
        start = true;
        document.getElementById("matching").style.visibility = "hidden";
        document.getElementById('matchingContent').textContent = "匹配成功";
        // login();
    } else if(parseInt(str[0]) == "2") {
        turn = true;
        document.getElementById("yourturn").style.visibility = "visible"
        setTimeout("document.getElementById('yourturn').style.visibility = 'hidden'",3000);
        console.log("you turn!");
    } else if(parseInt(str[0]) == "3") {
        play(parseInt(str[1]),parseInt(str[2]));
    } else if(parseInt(str[0]) == "4") {
        setTimeout("onClose('Win')",1000);
        var ret = confirm("Congratulation! You Win! \n Play Again ?");
        if(ret) {
            document.location.reload();
        } else {
            console.log("win");
            document.location.replace("../html/blank.html");
        }
        console.log("you win!");
    } else if(parseInt(str[0]) == "5") {
        setTimeout("onClose('Fail')",1000);
        var ret = confirm("Sorry, You Fail. \n Play Again ?");
        if(ret) {
            document.location.reload();
        } else {
            console.log("fail");
            document.location.replace("../html/blank.html");
        }
        console.log("you fail");
    } else if(parseInt(str[0]) == "6") {
        setTimeout("onClose('Draw')",1000);
        var ret = confirm("Draw ! \n Play Again ?\n");
        if(ret) {
            document.location.reload();
        } else {
            console.log("draw");
            document.location.replace("../html/blank.html");
        }
        console.log("draw");
    }
}
function onClose(evt) {
    ws.close();
    console.log("close");
    console.log(evt);
}
function onError(evt) {
    console.log("error");
    console.log(evt);
}
function sendMsg(evt) {
    if(isconnect) {
        ws.send(evt);
    }
} 

/********* Chess board0 *********/
//获取棋盘canvas
var chess = document.getElementById("chess");
//获取2d画布
var context = chess.getContext('2d');
//指定当前是否黑色下，只在UI中使用
var me = true;
//指定当前位置是否下了棋，1代表黑，2代表白，0代表空
curIndex = [];
var row = 10;
var col = 10;
var line = 11;
var isconnect = false;
var curIndex = [];
for(var i =0; i <row; i++) {
    curIndex[i] = [];
    for(var j =0; j <col; j++)
        curIndex[i][j] = 0;
}
drawtable();

//绘制棋盘
function drawtable() {
    //我们设置棋盘总共11根横线11根纵线，左右上下都有50px的边距，其中每个棋子相距50px,因此绘制棋盘从25px开始
    for(var i =0; i <line; i++)
        for(var j =0; j <line; j++)
            {
                //绘制横线
                context.moveTo(25, 25 +j *50);
                context.lineTo(525, 25 +j *50);
                //绘制竖线
                context.moveTo(25 +j *50, 25);
                context.lineTo(25 +j *50, 525); 

                //使用灰色描边
                context.strokeStyle = "#bfbfbf";
                context.stroke();
            }
};

//获取棋子位置
chess.onclick = function(event) {
    //获取要下的棋子的位置
    var x = Math.floor((event.offsetX-25)/50);
    var y = Math.floor((event.offsetY -25)/50);
    if(turn) {
        play(x,y);
    }
}
//落子
function play(x, y) {
    //判断是否溢出棋盘边界
    if(x < 0 || y < 0) {
        return;
    }
    if(x >= row || y >= col) {
        return;
    }
    //判断该点是否已被下了
    if(curIndex[x][y] != 0) {
        return;
    }
    if(turn) {
        //发送棋子位置
        ws.send(2+" "+x+" "+y);
        turn = false;
    }
    console.log("("+x+","+y+")");
    //开始绘制
    context.beginPath();
    //绘制指定圆
    context.arc(50 +x *50, 50 +y *50, 25, 0, 2 *Math.PI);
    //进行填充
    if(me) {
        context.fillStyle = "#636766";
        curIndex[x][y] = 1;
        me = false;
    }
    else {
        context.fillStyle = "#b9b9b9";
        curIndex[x][y] = 2;
        me = true;
    }
    context.fill();
    //结束绘制
    context.closePath();
};


/************* main ************/
if(!start) {
    console.log("matchingContent");
    setInterval("document.getElementById('matchingContent').textContent = '正在匹配对手…'",1500);
    setInterval("document.getElementById('matchingContent').textContent = '正在匹配对手……'",2000);
}